package com.example.demoback.interceptor;

import com.example.demoback.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器实现token校验
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String requestURI = request.getRequestURI();
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            log.info("预检请求，放行");
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        if(token == null || token.isEmpty()) {
            log.info("令牌为空，响应代码401");
            response.setStatus(401);
            return false;
        }
        try {
            //解析令牌，一旦报错抛出异常
            JwtUtils.parseJWT(token);
        }catch (Exception e) {
            log.info("令牌非法："+e.getMessage());
            response.setStatus(401);
            return false;
        }

        //校验完毕，放行
        log.info("已经登录，请求放行");
        return true;
    }
}
